package com.ray.business.api;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ray.base.api.CustomerApi;
import com.ray.base.check.CustomerCheck;
import com.ray.base.service.BaseCustomerService;
import com.ray.base.service.compose.GoodsService;
import com.ray.base.table.entity.BaseCustomer;
import com.ray.base.table.params.customer.CustomerQueryParams;
import com.ray.base.table.vo.customer.CustomerVO;
import com.ray.base.table.vo.material.model.MaterialModelVO;
import com.ray.business.builder.*;
import com.ray.business.check.BusinessCheck;
import com.ray.business.check.OrderCheck;
import com.ray.business.check.OrderGoodsCheck;
import com.ray.business.check.OrderStepCheck;
import com.ray.business.service.*;
import com.ray.business.table.dto.BusinessQueryDTO;
import com.ray.business.table.dto.BusinessQuickQueryDTO;
import com.ray.business.table.entity.*;
import com.ray.business.table.params.business.*;
import com.ray.business.table.params.business.quick.BusinessQuickGoodsQueryParams;
import com.ray.business.table.params.business.quick.BusinessQuickQueryParams;
import com.ray.business.table.params.business.quick.BusinessQuickSubmitParams;
import com.ray.business.table.vo.BusinessGoodsVO;
import com.ray.business.table.vo.BusinessQuickVO;
import com.ray.business.table.vo.BusinessVO;
import com.ray.business.table.vo.QuickSearchGoodsVO;
import com.ray.common.check.AbstractCheck;
import com.ray.magicBlock.BlockDispatch;
import com.ray.system.builder.CommonPageBuilder;
import com.ray.system.service.SysUserService;
import com.ray.system.table.entity.SysUser;
import com.ray.util.CodeCreateUtil;
import com.ray.util.CodeSplitUtil;
import com.ray.validate.support.utils.ValidateUtil;
import com.ray.wms.service.WmsWarehouseService;
import com.ray.wms.table.entity.WmsWarehouse;
import com.ray.woodencreate.beans.LoginUser;
import com.ray.woodencreate.enums.YesOrNoEnum;
import com.ray.woodencreate.exception.BusinessExceptionFactory;
import com.ray.woodencreate.page.CommonPage;
import com.ray.woodencreate.result.MsgCodeConstant;
import com.ray.woodencreate.result.Result;
import com.ray.woodencreate.result.ResultFactory;
import com.ray.woodencreate.util.Assert;
import com.ray.woodencreate.util.LogInUserUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.validation.Valid;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @author bo shen
 * @Description: 订单相关服务
 * @Class: BusinessApi
 * @Package com.ray.base.api
 * @date 2020/5/27 11:15
 * @company <p>Ray快速开发平台</p>
 * @updateRecord time(修改时间)  author(修改人)   desc(修改内容)
 */
@Service
@Slf4j
public class BusinessQuickApi {

    @Autowired
    private ProdBusinessQuickService prodBusinessQuickService;
    @Autowired
    private ProdBusinessQuickInService prodBusinessQuickInService;
    @Autowired
    private ProdOrderStepService prodOrderStepService;
    @Autowired
    private BaseCustomerService baseCustomerService;
    @Autowired
    private ProdStepService prodStepService;
    @Autowired
    private SysUserService sysUserService;
    @Autowired
    private BusinessApi businessApi;
    @Autowired
    private ProdBusinessService prodBusinessService;
    @Autowired
    private ProdBusinessOutService prodBusinessOutService;

    @Autowired
    private BlockDispatch<BusinessQuickGoodsQueryParams, LoginUser, BusinessGoodsVO> goodsDispatch;

    /**
     * 查询当前验布信息
     *
     * @param quickQueryParams
     * @return
     */
    public Result<BusinessQuickVO> viewBusinessQuick(BusinessQuickQueryParams quickQueryParams) {
        ValidateUtil.validate(quickQueryParams);

        LoginUser loginUser = LogInUserUtil.get();
        BusinessQuickQueryDTO businessQuickQueryDTO = new BusinessQuickQueryDTO();
        BeanUtil.copyProperties(quickQueryParams, businessQuickQueryDTO);
        //查询
        ProdBusinessQuick prodBusinessQuick = prodBusinessQuickService.queryEntity(businessQuickQueryDTO, loginUser);
        if (ObjectUtil.isNull(prodBusinessQuick)) {
            //查询仓库信息
            ProdOrderStep prodOrderStep = prodOrderStepService.queryStepByStepCode(CodeSplitUtil.getFirst(quickQueryParams.getGoodsCode()), quickQueryParams.getStepCode(), loginUser);
            prodBusinessQuick = new BusinessQuickBuilder().append(quickQueryParams).append(prodOrderStep).appendStatus(YesOrNoEnum.NO.getValue())
                    .appendCreate(loginUser).bulid();
            prodBusinessQuickService.save(prodBusinessQuick);
        }

        BusinessQuickVOBuilder businessVOBuilder = new BusinessQuickVOBuilder();
        businessVOBuilder.append(prodBusinessQuick);
        //查询客户信息
        BaseCustomer baseCustomer = baseCustomerService.queryCustomerByCustomerCode(prodBusinessQuick.getCustomerCode(), loginUser);
        businessVOBuilder.append(baseCustomer);
        //查询工序
        ProdStep prodStep = prodStepService.queryStepByStepCode(prodBusinessQuick.getStepCode(), loginUser);
        businessVOBuilder.append(prodStep);
        //查询人员信息
        if (StrUtil.isNotBlank(prodBusinessQuick.getEmployee())) {
            SysUser user = sysUserService.queryUserByUserCode(prodBusinessQuick.getEmployee(), loginUser);
            businessVOBuilder.appendEmployee(user);
            //查询人员信息
            SysUser usera = sysUserService.queryUserByUserCode(prodBusinessQuick.getEmployeea(), loginUser);
            businessVOBuilder.appendEmployeeA(usera);
        }
        return ResultFactory.createSuccessResult(MsgCodeConstant.Success.SUC00000002, businessVOBuilder.bulid());
    }


    /**
     * 删除
     *
     * @return
     */
    @Transactional
    public Result<String> deleteBusinessQuick(String quickCode) {
        //当前登录对象
        LoginUser loginUser = LogInUserUtil.get();
        ProdBusinessQuick prodBusinessQuick = prodBusinessQuickService.queryBusinessQuickByQuickCode(quickCode, loginUser);
        new AbstractCheck<>(prodBusinessQuick).checkNull("快捷入库单不存在");
        BusinessQuickBuilder businessQuickBuilder = new BusinessQuickBuilder().appendCode(quickCode).appendEdit(loginUser).delete();
        if (!prodBusinessQuickService.edit(businessQuickBuilder.bulid(), loginUser)) {
            log.info("删除快捷入库异常");
            throw BusinessExceptionFactory.newException("删除快捷入库异常");
        }
        return ResultFactory.createSuccessResult(MsgCodeConstant.Success.SUC00000002, quickCode);
    }


    /**
     * 提交
     *
     * @return
     */
    @Transactional
    public Result<String> submitBusinessQuick(BusinessQuickSubmitParams submitParams) {
        //当前登录对象
        LoginUser loginUser = LogInUserUtil.get();
        ProdBusinessQuick prodBusinessQuick = prodBusinessQuickService.queryBusinessQuickByQuickCode(submitParams.getQuickCode(), loginUser);
        new AbstractCheck<>(prodBusinessQuick).checkNull("快捷入库单不存在");
        BusinessQuickBuilder businessQuickBuilder = new BusinessQuickBuilder().append(submitParams).
                appendCode(submitParams.getQuickCode()).appendStatus(YesOrNoEnum.YES.getValue()).appendEdit(loginUser).delete();
        if (!prodBusinessQuickService.edit(businessQuickBuilder.bulid(), loginUser)) {
            log.info("更新快捷入库异常");
            throw BusinessExceptionFactory.newException("更新快捷入库异常");
        }
        //查询快捷
        List<ProdBusinessQuickIn> quickIns = prodBusinessQuickInService.listByQuickCode(submitParams.getQuickCode(), loginUser);
        if (ObjectUtil.isEmpty(quickIns)) {
            log.info("更新快捷入库无记录异常");
            throw BusinessExceptionFactory.newException("更新快捷入库无记录异常");
        }
        //提交验布入库信息
        BusinessCreateParams createParams = new BusinessCreateParams();
        List<BusinessGoodsParams> goods = quickIns.parallelStream().map(prodBusinessQuickIn -> {
            BusinessGoodsParams businessGoodsParams = new BusinessGoodsParams();
            BeanUtil.copyProperties(prodBusinessQuickIn, businessGoodsParams);
            businessGoodsParams.setCode(prodBusinessQuickIn.getOutCode());
            //快速入库默认1
            businessGoodsParams.setTotal(1);
            return businessGoodsParams;
        }).collect(Collectors.toList());
        BeanUtil.copyProperties(prodBusinessQuick, createParams);
        createParams.setPrice(submitParams.getPrice());
        createParams.setEmployee(submitParams.getEmployee());
        createParams.setEmployeea(submitParams.getEmployeea());
        createParams.setGoods(goods);
        createParams.setTotal(goods.size());
        createParams.setOutBusinessCode(submitParams.getOutBusinessCode());
        businessApi.createBusinessIn(createParams);
        return ResultFactory.createSuccessResult(MsgCodeConstant.Success.SUC00000002, submitParams.getQuickCode());
    }

    /**
     * 查询商品信息
     *
     * @param quickQueryParams
     * @return
     */
    public Result<BusinessGoodsVO> viewGoods(BusinessQuickGoodsQueryParams quickQueryParams) {
        LoginUser loginUser = LogInUserUtil.get();
        BusinessGoodsVO businessGoodsVO = goodsDispatch.dispatch("businessGoods", quickQueryParams.getType(), quickQueryParams, loginUser);
        return ResultFactory.createSuccessResult(MsgCodeConstant.Success.SUC00000002, businessGoodsVO);
    }

    /**
     * 快速检索
     *
     * @param quickQueryParams
     * @return
     */
    public Result<QuickSearchGoodsVO> search(NumberQueryParams quickQueryParams) {
        LoginUser loginUser = LogInUserUtil.get();
        List<ProdBusinessOut> outs = prodBusinessOutService.listByNumber(quickQueryParams.getSerialNumber(), loginUser);
        if(ObjectUtil.isEmpty(outs)){
            throw  BusinessExceptionFactory.newException("序列号没有出库");
        }
        ProdBusinessOut prodBusinessOut  = outs.get(0);
        if(prodBusinessOut.getStatus() == YesOrNoEnum.NO.getValue().intValue()){
            throw  BusinessExceptionFactory.newException("序列号已入库");
        }
        ProdBusiness prodBusiness = prodBusinessService.queryBusinessByBusinessCode(prodBusinessOut.getBusinessCode(),loginUser);
        new BusinessCheck(prodBusiness).checkNull("加工单号不存在");

        QuickSearchGoodsVO quickSearchGoodsVO = new QuickSearchGoodsVO();
        quickSearchGoodsVO.setCustomerCode(prodBusiness.getCustomerCode());
        quickSearchGoodsVO.setStepCode(prodBusiness.getStepCode());
        quickSearchGoodsVO.setGoodsCode(prodBusiness.getGoodsCode());
        quickSearchGoodsVO.setOrderNo(prodBusiness.getOrderNo());
        return ResultFactory.createSuccessResult(MsgCodeConstant.Success.SUC00000002, quickSearchGoodsVO);
    }
}
